<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/cropper.min.css" />
		<link rel="stylesheet" href="../css/mui.cropper.css" />
		<link rel="stylesheet" href="../css/my.css" />
	</head>

	<body>
		<div class="mui-content" style="position: static;height: 100vh;">
			<div class="mui-card card" style="padding: 0;margin: 0;">
				<div class="mui-card-media">
					<div>
						<img src="../img/logo.png" id="avatar" />
					</div>
					<div>
						<h5 style="color: white;" id="changeAvatar">点击修改</h5>
					</div>
				</div>
			</div>
			<div id="loginDiv" class="content-div">
				<form class="mui-input-group">
					<div class="mui-input-row">
						<label>用户名：</label>
						<input id="userInput" type="text" class="mui-input-clear">
					</div>
					<div class="mui-input-row">
						<label>密&nbsp;&nbsp;&nbsp;&nbsp;码：</label>
						<input id="passInput" type="password" class="mui-input-password">
					</div>
				</form>
				<div class="btn-div">
					<button id="loginBtn" type="button" class="mui-btn mui-btn-red login-btn">登录</button>
					<div style="width: 5px;"></div>
					<button id="regBtn" type="button" class="mui-btn mui-btn-red login-btn">注册</button>
				</div>
			</div>
			<div class="info-div content-div" id="userInfoDiv">
				<h3>欢迎回来</h3>
				<h3 id="userIdSpan">用户名</h3>
				<button id="logOutBtn" type="button" class="mui-btn mui-btn-red mui-btn-block" style="">注销</button>
			</div>
		</div>
		<div class="mui-cropper-modal mui-modal">
			<div class="cropper-image-container">
				<img id="image" src="" />
			</div>
			<div class="cropper-btn-group">
				<span class="cropper-cancel">取消</span>
				<span class="cropper-ok">裁剪</span>
			</div>
		</div>
		<script type="text/javascript" src="../js/lib/mui.min.js"></script>
		<script src="../js/lib/cropper.min.js"></script>
		<script src="../js/lib/mui.cropper.js"></script>
		<script type="text/javascript" src="../js/util.js"></script>
		<script type="text/javascript" src="../js/lib/CryptoJS.js"></script>
		<script type="text/javascript" src="../js/qiniu.js"></script>
		<script type="text/javascript">
			var dbName = 'hb_news_db';
			var db;
			var ak = "4F1leE9jvVyiRCDQMIQvg74g3lRkfqswLPAiNCB8";
			var sk = "5tQbbgueb4ZK8BksJoNHsdv1XjzgGxkLYEWlcAsI";
			var imgUrl = "http://ozvckep4q.bkt.clouddn.com/";
			mui.init();
			mui.plusReady(function() {
				dragHandler(3);
				initDb();
				setUserInfo();
				document.getElementById('loginBtn').addEventListener('tap', function() {
					login();
				});
				document.getElementById('regBtn').addEventListener('tap', function() {
					register();
				});
				document.getElementById('logOutBtn').addEventListener('tap', function() {
					logout();
				});

			});
			document.getElementById('changeAvatar').addEventListener('tap', function() {
				showChangeAvatarMenu();
			});

			function initDb() {
				db = openDatabase(dbName, '1.0', 'hbuilder news demo', 2 * 1024 * 1024);
				db.transaction(function(tx) {
					tx.executeSql('CREATE TABLE IF NOT EXISTS user (id text primary key asc, password text, avatar text)');
				});
			}

			function setUserInfo() {
				if(localStorage.getItem('userid')) {
					document.getElementById("loginDiv").style.display = 'none';
					document.getElementById("userInfoDiv").style.display = '';
					document.getElementById("changeAvatar").style.display = '';
					document.getElementById("userIdSpan").innerHTML = localStorage.getItem('userid');
					if(localStorage.getItem('avatar')) {
						document.getElementById("avatar").src = imgUrl+localStorage.getItem('avatar');
					} else {
						document.getElementById("avatar").src = '../img/logo.png';
					}
				} else {
					document.getElementById("loginDiv").style.display = '';
					document.getElementById("userInfoDiv").style.display = 'none';
					document.getElementById("changeAvatar").style.display = 'none';
					document.getElementById("avatar").src = '../img/logo.png';
				}
			}

			function login() {
				var userid = document.getElementById('userInput').value;
				var password = document.getElementById('passInput').value;
				if(checkForm()) {
					db.transaction(function(tx) {
						tx.executeSql('select * from user where id=? and password=?', [userid, password], function(tx, res) {
							if(res.rows.length > 0) {
								localStorage.setItem('userid', userid);
								if(res.rows.item(0).avatar) {
									localStorage.setItem('avatar', res.rows.item(0).avatar);
								}
								setUserInfo();
							} else {
								mui.toast('您还未注册，请先注册！');
							}
						}, function(tx, error) {
							mui.toast('输入有误，请您重试！');
						});
					});
				}
			}

			function register() {
				var userid = document.getElementById('userInput').value;
				var password = document.getElementById('passInput').value;
				if(checkForm()) {
					db.transaction(function(tx) {
						tx.executeSql("INSERT INTO user (id,password,avatar) VALUES (?, ? ,?)", [userid, password, null], function(data) {
							localStorage.setItem("userid", userid);
							setUserInfo();
						}, function(tx, error) {
							console.log('ERROR occurred in inserting records');
							mui.toast('输入有误，请您更换用户名后重试！');
						});
					});
				}
			}

			function logout() {
				localStorage.removeItem('userid');
				localStorage.removeItem('avatar');
				setUserInfo();
			}

			function checkForm() {
				var userid = document.getElementById('userInput').value
				var password = document.getElementById('passInput').value
				if(userid.length == 0) {
					mui.toast('请输入用户名！');
					return false;
				} else if(password.length == 0) {
					mui.toast('请输入密码！');
					return false;
				} else {
					return true;
				}
			}

			function showChangeAvatarMenu() {
				if(mui.os.plus) {
					var a = [{
						title: "拍照"
					}, {
						title: "从手机相册选择"
					}];

					plus.nativeUI.actionSheet({
						title: "修改用户头像",
						cancel: "取消",
						buttons: a
					}, function(b) {
						switch(b.index) {
							case 0:
								break;
							case 1:
								/*拍照*/
								mui.captureImage(function(path) {
									var fullPath = mui.getLocalFileURL(path);
									handleCropper(fullPath);
								});
								break;
							case 2:
								/*打开相册*/
								mui.pickGallery(function(path) {
									handleCropper(path);
								});
								break;
							default:
								break;
						}
					});
				}
			}

			function handleCropper(path) {
				mui.cropper.show(path, function(data) {
					mui.saveImage(data, '_doc/tmp.jpg',
						function(path) {
							plus.io.resolveLocalFileSystemURL('_doc/avatar.jpg', function(entry) {
								entry.remove(function(entry) {
									compressImage(path);
								});
							}, function(e) {
								compressImage(path);
							});
						}
					);
				});
			}

			function compressImage(path) {
				plus.zip.compressImage({
						src: "_doc/tmp.jpg",
						dst: "_doc/avatar.jpg",
						quality: 40
					},
					function() {
						var avatarPath = path.replace('tmp', 'avatar');
						document.getElementById("avatar").src = avatarPath + "?" + new Date().getTime();
						upload(avatarPath);
					},
					function(error) {
						console.log(JSON.stringify(error));
					}
				);
			}

			function upload(avatarPath) {
				var wt = plus.nativeUI.showWaiting();
				var task = plus.uploader.createUpload("http://upload-z1.qiniup.com", {
						method: "POST"
					},
					function(t, status) {
						var data = JSON.parse(t.responseText);
						if(status == 200) {
							db.transaction(function(tx) {
								var sql = "update user set avatar=? where id=?";
								tx.executeSql(sql, [data.key,localStorage.getItem('userid')], function(data) {
									mui.toast('头像修改成功！');
								}, function(tx, error) {
									console.log('ERROR occurred in inserting records');
									mui.toast('头像修改失败！请确认操作无误后重试！');
								});
							});
							wt.close();
						} else {
							mui.toast("上传失败：" + status);
							wt.close();
						}
					}
				);
				var uid = Math.floor(Math.random() * 100000000 + 10000000).toString();
				var scope = "fish119";
				var type = uid + ".jpg";
				var putPolicy = {
					scope: scope + ":" + type,
					deadline: new Date().getTime()
				}
				var token = genUpToken(ak, sk, putPolicy);
				task.addData("key", type);
				task.addData("scope", scope);
				task.addData("token", token);
				task.addFile(avatarPath, {
					"key": "file",
					"name": "file"
				});
				task.start();
			}
		</script>
	</body>

</html>